<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;
use Dcat\Admin\Admin;


class UserController extends Controller
{

    public function login(Request $request)
    {
        $data = $request->all();
        $username= $data['username'];
        $password = $data['password'];

        if(empty($username) || empty($password)){
            return $this->ErrJson(201,'账号密码不能为空');
        }

        if(!Admin::guard()->attempt(['username'=>$username,'password'=>$password])){
            return $this->ErrJson(202,'账号密码错误');
        }

        $user_info = DB::table('admin_users')->where('username',$username)->first();

        $token = Str::random(100);
        $secureToken = hash_hmac('sha256', $token, 'salt');

        DB::table('admin_users')->where('id',$user_info->id)->update(['token'=>$secureToken]);

        $user_info = DB::table('admin_users')->where('username',$username)->first();
        return $this->OkJson($user_info);
    }




    public function getUserInfoByCode(Request $request)
    {
        $data = $request->json()->all();
        $code = $data['code'];
        $user_info = $this->isLogin($data['token']);
        if(!$user_info){
            return $this->ErrJson(203,'请先登录');
        }

        $appid = 'wx8556335119bca8a1';

        $secret = 'e4d9383c8eb16d8ef6aa6565f6066f1a';

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid. "&secret=".$secret . "&js_code=".$code ."&grant_type=authorization_code";

        $wxuserinfo = file_get_contents($url,true);
        $openid = json_decode($wxuserinfo,true)['openid'];

        DB::table('users')->where('id',$user_info->id)->update(['openid'=>$openid]);
        return $this->OkJson("授权成功");
    }



    public function existOpenid(Request $request)
    {
        $data = $request->json()->all();
        $user_info = $this->isLogin($data['token']);
        if(!$user_info){
            return $this->ErrJson(203,'请先登录');
        }

        if(empty($user_info->openid)){
            return $this->ErrJson(210,'openid不存在');
        }

        return $this->OkJson("存在");
    }

}
